<template>
  <el-card>
    <div style="margin-bottom: 16px;">
      <el-button type="primary" @click="showDialog = true">新增二级类型</el-button>
    </div>

    <el-table :data="instrumentSubTypes" style="width: 100%;" border>
      <el-table-column label="序号" prop="id" width="180" />
      <el-table-column label="二级类型名称" prop="name" />

      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button type="danger" size="small" @click="deleteItem(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="showDialog" title="新增二级类型" width="400px">
      <el-form :model="newSubType" label-width="100px">
        <el-form-item label="类型名称">
          <el-input v-model="newSubType.name" placeholder="请输入名称" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="create">确认添加</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getInstrumentSubTypes, deleteInstrumentSubType} from '@/apps/admin/utils/instrumentApi'
import request from "@/apps/admin/utils/request.js"

const instrumentSubTypes = ref([])
const showDialog = ref(false)

const newSubType = ref({
  name: ''
})

const fetch = async () => {
  try {
    const res = await getInstrumentSubTypes()
    instrumentSubTypes.value = res.data
  } catch (err) {
    console.error(err)
    ElMessage.error('加载失败')
  }
}

const create = async () => {
  if (!newSubType.value.name) {
    ElMessage.warning('请填写类型名称')
    return
  }

  try {
    const res = await request.post("/v1/admin/createInstrumentSubType", newSubType.value)
    if (res.code !== 200) {
      ElMessage.error(res.msg || '添加失败')
      return
    }
    ElMessage.success('添加成功')
    await fetch()
    showDialog.value = false
    newSubType.value = { name: '' }
  } catch (err) {
    console.error(err)
    ElMessage.error(err?.response?.data?.msg || '添加失败')
  }
}


const deleteItem = async (id) => {
  try {
    const res = await deleteInstrumentSubType({ id })
    if (res.code !== 200) {
      ElMessage.error(res.msg || '删除失败')
      return
    }
    await fetch()
    ElMessage.success('删除成功')
  } catch (err) {
    console.error(err)
    ElMessage.error(err?.response?.data?.msg || '删除失败')
  }
}


onMounted(fetch)
</script>
